<template>
	<el-container class="group-page im-container">
		<el-aside :width="asideWidth + 'px'" class="aside">
			<div class="header">
				<el-input class="search-text" size="small" placeholder="搜索群聊" v-model="searchText">
					<template #prefix>
						<i class="fas fa-search"></i>
					</template>
				</el-input>
				<el-button plain class="add-btn" title="创建群聊" @click="onCreateGroup()">
					<i class="fas fa-plus"></i>
				</el-button>
			</div>
			<el-scrollbar class="group-items" v-if="groupStore.groups && groupStore.groups.length > 0">
				<div v-for="(groups, i) in groupValues" :key="i">
					<div class="letter">{{ groupKeys[i] }}</div>
					<div v-for="group in groups" :key="group.id">
						<group-item :group="group" :active="group.id == activeGroup.id"
							@click.native="onActiveItem(group)" @chat="onSendMessage(group)"
							@info="onActiveItem(group)">
						</group-item>
					</div>
					<div v-if="i < groupValues.length - 1" class="divider"></div>
				</div>
			</el-scrollbar>

			<!-- 空状态 -->
			<div v-else class="empty-group-list">
				<div class="empty-content">
					<i class="fas fa-users empty-icon"></i>
					<h3 class="empty-title">暂无群聊</h3>
					<p class="empty-desc">创建或加入群聊，与更多朋友一起畅聊</p>
					<div class="empty-actions">
						<el-button type="primary" @click="onCreateGroup" class="action-btn">
							<i class="fas fa-plus"></i>
							创建群聊
						</el-button>
					</div>
				</div>
			</div>

			<!-- 水平拉伸分隔器 -->
			<resizable-divider direction="horizontal" :min-width="200" :max-width="400" @resize="handleAsideResize" />
		</el-aside>
		<el-container class="container">
			<div class="header" v-show="activeGroup.id">{{ activeGroup.showGroupName }}({{ showMembers.length }})</div>
			<div class="container-box" v-show="activeGroup.id">
				<div class="group-info">
					<div>
						<file-upload v-show="isOwner" class="avatar-uploader" :action="imageAction" :showLoading="true"
							:maxSize="maxSize" @success="onUploadSuccess"
							:fileTypes="['image/jpeg', 'image/png', 'image/jpg', 'image/webp']">
							<img v-if="activeGroup.headImage" :src="activeGroup.headImage" class="avatar">
							<i v-else class="fas fa-camera avatar-uploader-icon"></i>
						</file-upload>
						<head-image v-show="!isOwner" class="avatar" :size="160" :url="activeGroup.headImage"
							:name="activeGroup.showGroupName" radius="10%" @click.native="showFullImage()">
						</head-image>
						<el-button class="send-btn" type="primary" @click="onSendMessage()">
							<i class="fas fa-comment-dots"></i> 发消息
						</el-button>
					</div>
					<el-form class="form" label-width="130px" :model="activeGroup" :rules="rules" size="small"
						ref="groupForm">
						<el-form-item label="群聊名称" prop="name">
							<el-input v-model="activeGroup.name" :disabled="!isOwner" maxlength="20"></el-input>
						</el-form-item>
						<el-form-item label="群主">
							<el-input :value="ownerName" disabled></el-input>
						</el-form-item>
						<el-form-item label="群名备注">
							<el-input v-model="activeGroup.remarkGroupName" :placeholder="activeGroup.name"
								maxlength="20"></el-input>
						</el-form-item>
						<el-form-item label="我在本群的昵称">
							<el-input v-model="activeGroup.remarkNickName" maxlength="20"
								:placeholder="userStore.userInfo.nickName"></el-input>
						</el-form-item>
						<el-form-item label="群公告">
							<el-input v-model="activeGroup.notice" :disabled="!isOwner" type="textarea" :rows="3"
								maxlength="1024" placeholder="群主未设置"></el-input>
						</el-form-item>
						<div>
							<el-button type="warning" @click="onInvite()">
								<i class="fas fa-user-plus"></i> 邀请
							</el-button>
							<el-button type="success" @click="onSaveGroup()">
								<i class="fas fa-save"></i> 保存
							</el-button>
							<el-button type="danger" v-show="!isOwner" @click="onQuit()">
								<i class="fas fa-sign-out-alt"></i> 退出
							</el-button>
							<el-button type="danger" v-show="isOwner" @click="onDissolve()">
								<i class="fas fa-trash-alt"></i> 解散
							</el-button>
						</div>
					</el-form>
				</div>
				<el-divider content-position="center"></el-divider>
				<el-scrollbar ref="scrollbar" :style="'height: ' + scrollHeight + 'px'">
					<div class="member-items">
						<div class="member-tools">
							<div class="tool-btn" title="邀请好友进群聊" @click="onInvite()">
								<i class="fas fa-user-plus"></i>
							</div>
							<div class="tool-text">邀请</div>
							<add-group-member ref="addGroupMember" :groupId="activeGroup.id" :members="groupMembers"
								@reload="loadGroupMembers"></add-group-member>
						</div>
						<div class="member-tools" v-if="isOwner">
							<div class="tool-btn" title="选择成员移出群聊" @click="onRemove()">
								<i class="fas fa-user-minus"></i>
							</div>
							<div class="tool-text">移除</div>
							<group-member-selector ref="removeSelector" title="选择成员进行移除" :group="activeGroup"
								@complete="onRemoveComplete"></group-member-selector>
						</div>
						<div v-for="(member, idx) in showMembers" :key="member.id">
							<group-member v-if="idx < showMaxIdx" class="member-item" :member="member"></group-member>
						</div>
					</div>
				</el-scrollbar>
			</div>
			<div v-show="!activeGroup.id" class="content-empty-state">
				<i class="welcome-icon fas fa-users"></i>
				<h3 class="welcome-title">选择一个群聊查看详情</h3>
				<p class="welcome-desc">从左侧选择一个群聊，查看群信息和成员列表</p>
			</div>
		</el-container>
	</el-container>
</template>


<script>
import GroupItem from '@/components/IMGroup/GroupItem.vue';
import FileUpload from '@/components/common/FileUpload.vue';
import GroupMember from '@/components/IMGroup/GroupMember.vue';
import AddGroupMember from '@/components/IMGroup/AddGroupMember.vue';
import GroupMemberSelector from '@/components/IMGroup/GroupMemberSelector.vue';
import HeadImage from '@/components/common/HeadImage.vue';
import ResizableDivider from '@/components/common/ResizableDivider.vue';
import { pinyin } from 'pinyin-pro';
import {
	createGroupApi,
	removeGroupMembersApi,
	modifyGroupApi,
	deleteGroupApi,
	quitGroupApi,
	getGroupMembersApi
} from '@/api/imGroup.js';
import { getAsideWidth, saveAsideWidth, debounce } from "@/utils/im/layoutPreferences.js";

export default {
	name: "IMGroup",
	components: {
		GroupItem,
		GroupMember,
		FileUpload,
		AddGroupMember,
		GroupMemberSelector,
		HeadImage,
		ResizableDivider
	},
	data() {
		return {
			searchText: "",
			maxSize: 5 * 1024 * 1024,
			activeGroup: {},
			groupMembers: [],
			showAddGroupMember: false,
			showMaxIdx: 150,
			asideWidth: getAsideWidth('group'), // 侧边栏宽度，从本地存储恢复
			rules: {
				name: [{
					required: true,
					message: '请输入群聊名称',
					trigger: 'blur'
				}]
			}
		};
	},
	methods: {
		// 处理侧边栏拉伸
		handleAsideResize(size) {
			if (size.width) {
				this.asideWidth = size.width;
				// 防抖保存到本地存储
				this.debouncedSaveAsideWidth(size.width);
			}
		},
		onCreateGroup() {
			this.$prompt('请输入群聊名称', '创建群聊', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				inputPattern: /\S/,
				inputErrorMessage: '请输入群聊名称'
			}).then(o => {
				let data = {
					name: o.value
				}
				createGroupApi(data).then((res) => {
					this.groupStore.addGroup(res.data);
					this.onActiveItem(res.data)
					this.$message.success('创建成功');
				}).catch((error) => {
					this.$message.error("创建群聊失败：" + (error.message || "未知错误"));
				})
			})
		},
		onActiveItem(group) {
			this.showMaxIdx = 150;
			// store数据不能直接修改，所以深拷贝一份内存
			this.activeGroup = JSON.parse(JSON.stringify(group));
			// 重新加载群成员
			this.groupMembers = [];
			this.loadGroupMembers();
		},
		onInvite() {
			this.$refs.addGroupMember.open();
		},
		onRemove() {
			// 群主不显示
			let hideIds = [this.activeGroup.ownerId];
			this.$refs.removeSelector.open(50, [], [], hideIds);
		},
		onRemoveComplete(members) {
			let userIds = members.map(m => m.userId);
			let data = {
				groupId: this.activeGroup.id,
				userIds: userIds
			}
			removeGroupMembersApi(data).then(() => {
				this.loadGroupMembers();
				this.$message.success(`您移除了${userIds.length}位成员`);
			}).catch((error) => {
				this.$message.error("移除成员失败：" + (error.message || "未知错误"));
			})
		},
		onUploadSuccess(data) {
			this.activeGroup.headImage = data.originUrl;
			this.activeGroup.headImageThumb = data.thumbUrl;
		},
		onSaveGroup() {
			this.$refs['groupForm'].validate((valid) => {
				if (valid) {
					let vo = this.activeGroup;
					modifyGroupApi(vo).then((res) => {
						this.groupStore.updateGroup(res.data);
						this.$message.success("修改成功");
					}).catch((error) => {
						this.$message.error("修改群聊失败：" + (error.message || "未知错误"));
					})
				}
			});
		},
		onDissolve() {
			this.$confirm(`确认要解散'${this.activeGroup.name}'吗?`, '确认解散?', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				deleteGroupApi(this.activeGroup.id).then(() => {
					this.$message.success(`群聊'${this.activeGroup.name}'已解散`);
					this.groupStore.removeGroup(this.activeGroup.id);
					this.reset();
				}).catch((error) => {
					this.$message.error("解散群聊失败：" + (error.message || "未知错误"));
				});
			})
		},
		onQuit() {
			this.$confirm(`确认退出'${this.activeGroup.showGroupName}',并清空聊天记录吗？`, '确认退出?', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				quitGroupApi(this.activeGroup.id).then(() => {
					this.$message.success(`您已退出'${this.activeGroup.name}'`);
					this.groupStore.removeGroup(this.activeGroup.id);
					this.chatStore.removeGroupChat(this.activeGroup.id);
					this.reset();
				}).catch((error) => {
					this.$message.error("退出群聊失败：" + (error.message || "未知错误"));
				});
			})
		},
		/**
		 * 点击发消息按钮，跳转到聊天界面
		 * 注意：这里不更新会话时间，保持最近聊天记录的时间
		 */
		onSendMessage(group) {
			// 如果没有传入群组参数，使用当前激活的群组
			const targetGroup = group || this.activeGroup;
			let chat = {
				type: 'GROUP',
				targetId: targetGroup.id,
				showName: targetGroup.showGroupName,
				headImage: targetGroup.headImage,
				isDnd: targetGroup.isDnd
			};
			// 第二个参数为false，表示不更新会话时间
			this.chatStore.openChat(chat, false);
			this.chatStore.setActiveChat(0);
			this.$router.push("/im/chat");
		},
		onScroll(e) {
			const scrollbar = e.target;
			// 滚到底部
			if (scrollbar.scrollTop + scrollbar.clientHeight >= scrollbar.scrollHeight - 30) {
				if (this.showMaxIdx < this.showMembers.length) {
					this.showMaxIdx += 50;
				}
			}
		},
		showFullImage() {
			if (this.activeGroup.headImage) {
				this.$eventBus.$emit("openFullImage", this.activeGroup.headImage);
			}
		},
		loadGroupMembers() {
			getGroupMembersApi(this.activeGroup.id).then((res) => {
				this.groupMembers = res.data;
			}).catch((error) => {
				console.error("加载群成员失败：", error);
			})
		},
		reset() {
			this.activeGroup = {};
			this.groupMembers = [];
		},
		firstLetter(strText) {
			// 使用pinyin-pro库将中文转换为拼音
			let pinyinOptions = {
				toneType: 'none', // 无声调
				type: 'normal' // 普通拼音
			};
			let pyText = pinyin(strText, pinyinOptions);
			return pyText[0];
		},
		isEnglish(character) {
			return /^[A-Za-z]+$/.test(character);
		}
	},
	computed: {
		ownerName() {
			let member = this.groupMembers.find(m => m.userId == this.activeGroup.ownerId);
			return member && member.showNickName;
		},
		isOwner() {
			return this.activeGroup.ownerId == this.userStore.userInfo.id;
		},
		imageAction() {
			return "image";
		},
		groupMap() {
			// 按首字母分组
			let map = new Map();
			this.groupStore.groups.forEach((g) => {
				if (g.quit || (this.searchText && !g.showGroupName.includes(this.searchText))) {
					return;
				}
				let letter = this.firstLetter(g.showGroupName).toUpperCase();
				// 非英文一律为#组
				if (!this.isEnglish(letter)) {
					letter = "#"
				}
				if (map.has(letter)) {
					map.get(letter).push(g);
				} else {
					map.set(letter, [g]);
				}
			})
			// 排序
			let arrayObj = Array.from(map);
			arrayObj.sort((a, b) => {
				// #组在最后面
				if (a[0] == '#' || b[0] == '#') {
					return b[0].localeCompare(a[0])
				}
				return a[0].localeCompare(b[0])
			})
			map = new Map(arrayObj.map(i => [i[0], i[1]]));
			return map;
		},
		groupKeys() {
			return Array.from(this.groupMap.keys());
		},
		groupValues() {
			return Array.from(this.groupMap.values());
		},
		showMembers() {
			return this.groupMembers.filter((m) => !m.quit)
		},
		scrollHeight() {
			return Math.min(300, 80 + this.showMembers.length / 10 * 80);
		}
	},
	mounted() {
		let scrollWrap = this.$refs.scrollbar.$el.querySelector('.el-scrollbar__wrap');
		scrollWrap.addEventListener('scroll', this.onScroll);

		// 初始化防抖保存函数
		this.debouncedSaveAsideWidth = debounce((width) => {
			saveAsideWidth('group', width);
		}, 300);
	}
}
</script>

<style lang="scss" scoped>
@use "@/styles/variables.scss" as *;

.group-page {
	height: 100%;
	width: 100%;
	overflow: hidden; // 隐藏所有滚动条，防止页面出现左右滑动条
	box-sizing: border-box; // 确保边框和内边距不会导致溢出

	.aside {
		display: flex;
		flex-direction: column;
		background: var(--im-bg-secondary);
		border-right: var(--im-border);
		height: 100%;
		position: relative;

		.header {
			height: 60px;
			display: flex;
			align-items: center;
			padding: var(--im-spacing-lg);
			border-bottom: var(--im-border);
			background: var(--im-bg-primary);
			position: relative;

			// 添加微妙的阴影
			&::after {
				content: '';
				position: absolute;
				bottom: 0;
				left: 0;
				right: 0;
				height: 1px;
				background: linear-gradient(90deg, transparent, var(--im-border-color-light), transparent);
			}

			.search-text {
				flex: 1;
				margin-right: var(--im-spacing-sm);

				:deep(.el-input__wrapper) {
					border-radius: var(--im-border-radius-lg);
					border: var(--im-border);
					background: var(--im-bg-tertiary);
					transition: all var(--im-transition-base);

					&:hover {
						border-color: var(--im-color-primary);
					}

					&.is-focus {
						border-color: var(--im-color-primary);
						box-shadow: 0 0 0 2px rgba(var(--im-color-primary-rgb), 0.1);
					}
				}

				:deep(.el-input__prefix) {
					color: var(--im-text-color-secondary);
					display: flex;
					align-items: center;
					justify-content: center;
					height: 100%;
				}

				:deep(.el-input__inner) {
					color: var(--im-text-color-primary);
					background: transparent;

					&::placeholder {
						color: var(--im-text-color-placeholder);
					}
				}
			}

			.add-btn {
				padding: var(--im-spacing-sm) !important;
				margin-left: var(--im-spacing-sm);
				font-size: 16px;
				border-radius: var(--im-border-radius-round);
				border: var(--im-border);
				background: var(--im-bg-primary);
				color: var(--im-text-color-secondary);
				transition: all var(--im-transition-base);

				&:hover {
					background: var(--im-color-primary);
					color: white;
					border-color: var(--im-color-primary);
					transform: translateY(-1px);
				}
			}
		}

		.group-items {
			flex: 1;
			background: var(--im-bg-primary);
			padding: var(--im-spacing-xs) 0;

			// 隐藏水平滚动条
			:deep(.el-scrollbar__wrap) {
				overflow-x: hidden !important;
				padding-right: 4px; // 为滚动条留出空间
			}

			:deep(.el-scrollbar__bar.is-horizontal) {
				display: none !important;
			}

			.letter {
				text-align: left;
				font-size: var(--im-larger-size-larger);
				padding: 5px 15px;
				color: var(--im-text-color-light);
			}

			// 群聊列表容器
			>div {
				position: relative;

				// 为每个群聊项添加分隔效果（除了字母分组标题）
				>div:not(.letter):not(:last-child) {
					position: relative;

					&::after {
						content: '';
						position: absolute;
						bottom: 0;
						left: var(--im-spacing-xl);
						right: var(--im-spacing-xl);
						height: 1px;
						background: var(--im-border-color-light);
						opacity: 0.3;
					}
				}
			}
		}

		// 空状态样式
		.empty-group-list {
			flex: 1;
			display: flex;
			align-items: center;
			justify-content: center;
			background: var(--im-bg-primary);

			.empty-content {
				text-align: center;
				max-width: 300px;
				padding: var(--im-spacing-xl);

				.empty-icon {
					font-size: 64px;
					color: var(--im-color-primary);
					margin-bottom: var(--im-spacing-lg);
					opacity: 0.6;
					animation: pulse 2s infinite;
				}

				.empty-title {
					color: var(--im-text-color-primary);
					font-size: var(--im-font-size-lg);
					font-weight: 600;
					margin: 0 0 var(--im-spacing-sm) 0;
				}

				.empty-desc {
					color: var(--im-text-color-secondary);
					font-size: var(--im-font-size-base);
					margin: 0 0 var(--im-spacing-xl) 0;
					line-height: 1.5;
				}

				.empty-actions {
					.action-btn {
						border-radius: var(--im-border-radius-base);
						padding: var(--im-spacing-sm) var(--im-spacing-lg);
						font-size: var(--im-font-size-sm);
						transition: all var(--im-transition-base);

						&:hover {
							transform: translateY(-1px);
							box-shadow: var(--im-box-shadow-hover);
						}

						i {
							margin-right: var(--im-spacing-xs);
						}
					}
				}
			}
		}
	}

	.container {
		display: flex;
		flex-direction: column;
		background: var(--im-bg-primary);
		min-width: 0; // 防止flex子元素溢出
		flex: 1; // 占据剩余空间

		.header {
			height: 60px; // 与左侧搜索框区域高度对齐
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 0 12px;
			line-height: 60px;
			font-size: var(--im-font-size-larger);
			font-weight: var(--im-font-weight-semibold);
			color: var(--im-text-color-primary);
			background: var(--im-bg-primary);
			border-bottom: var(--im-border);
			box-sizing: border-box;
		}

		.el-divider--horizontal {
			margin: 16px 0;
		}

		.container-box {
			overflow: auto;
			padding: 20px;
			flex: 1;

			.group-info {
				display: flex;
				padding: 20px;

				// 头像区域 - 居中布局
				>div:first-child {
					display: flex;
					flex-direction: column;
					align-items: center;
					margin-right: 40px;

					// 发消息按钮样式 - 居中显示在头像下方
					.send-btn {
						margin-top: var(--im-spacing-lg);
						padding: var(--im-spacing-sm) var(--im-spacing-lg);
						border-radius: var(--im-border-radius-base);
						font-size: var(--im-font-size-base);
						font-weight: var(--im-font-weight-medium);
						transition: all var(--im-transition-base);

						&:hover {
							transform: translateY(-1px);
							box-shadow: var(--im-box-shadow-hover);
						}

						&:active {
							transform: translateY(0);
						}

						i {
							margin-right: var(--im-spacing-xs);
						}
					}
				}

				// 表单区域
				.form {
					flex: 1;
					max-width: 700px;
				}

				.avatar-uploader {
					--width: 160px;
					text-align: center; // 头像居中显示

					.el-upload {
						border: 1px dashed #d9d9d9 !important;
						border-radius: 6px;
						cursor: pointer;
						position: relative;
						overflow: hidden;
					}

					.el-upload:hover {
						border-color: #409EFF;
					}

					.avatar-uploader-icon {
						font-size: 28px;
						color: #8c939d;
						width: var(--width);
						height: var(--width);
						line-height: var(--width);
						text-align: center;
					}

					.avatar {
						width: var(--width);
						height: var(--width);
						display: block;
					}
				}
			}

			.member-items {
				padding: 0 12px;
				display: flex;
				align-items: center;
				flex-wrap: wrap;
				text-align: center;

				.member-item {
					margin-right: 5px;
				}

				.member-tools {
					display: flex;
					flex-direction: column;
					align-items: center;
					width: 60px;

					.tool-btn {
						width: 38px;
						height: 38px;
						line-height: 38px;
						border: var(--im-border);
						font-size: 14px;
						cursor: pointer;
						box-sizing: border-box;

						&:hover {
							border: #aaaaaa solid 1px;
						}
					}

					.tool-text {
						font-size: var(--im-font-size-smaller);
						text-align: center;
						width: 100%;
						height: 30px;
						line-height: 30px;
						white-space: nowrap;
						text-overflow: ellipsis;
						overflow: hidden
					}
				}

			}
		}

		.content-empty-state {
			flex: 1;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			padding: var(--im-spacing-xl);
			background: var(--im-bg-primary);
			text-align: center;

			.welcome-icon {
				font-size: 64px;
				color: var(--im-color-primary);
				margin-bottom: var(--im-spacing-lg);
				opacity: 0.8;
			}

			.welcome-title {
				color: var(--im-text-color-primary);
				font-size: var(--im-font-size-lg);
				font-weight: 600;
				margin: 0 0 var(--im-spacing-base) 0;
			}

			.welcome-desc {
				color: var(--im-text-color-secondary);
				font-size: var(--im-font-size-base);
				margin: 0;
				line-height: 1.5;
			}
		}
	}
}
</style>